home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4432 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  71 lines

  1. Path: gail.ripco.com!mambuhl
  2. From: mambuhl@ripco.com (Martin Ambuhl)
  3. Newsgroups: comp.lang.c
  4. Subject: Unable to check calloc`s
  5. Date: 4 Feb 1996 16:01:14 GMT
  6. Organization: Ripco Communications, Inc.
  7. Message-ID: <4f2l8a$c98@gail.ripco.com>
  8. NNTP-Posting-Host: golden.ripco.com
  9.  
  10. s910500@acs.csc.cuhk.hk (CHAN CHUN CHUNG)
  11. in <4emept$ifv@hpg30a.csc.cuhk.hk> asks:
  12.  
  13. >Could anyone tell me why the following line is complained by the
  14. >compiler?
  15.  
  16. >if ((float **x = (float **) calloc(9, sizeof(float *)))
  17. >   == 0) exit(1);
  18.  
  19. >What's the right way to check the calloc's return value?
  20.  
  21. Let's clean this up (not all changes are for errors) one step at a time.
  22.  
  23. 1) Declarations go at the top of a block.  Let's make a block for context:
  24.     {
  25.         float **x;
  26.         if (x = (float **) calloc(9, sizeof(float *))) == 0) exit(1);
  27.     }
  28.  
  29. 2) exit(1) is not portable.  If you want to return a failure code,
  30.     the portable way is:
  31.     #include <stdlib.h>
  32.     {
  33.         float **x;
  34.         if (x = (float **) calloc(9, sizeof(float *))) == 0)
  35.             exit(EXIT_FAILURE);
  36.     }
  37.  
  38. 3) casting the return from ?alloc may mask the failure to #include
  39.     <stdlib.h>.  If you know enough about the proper cast to specify it,
  40.     then you don't need it:
  41.     #include <stdlib.h>
  42.     {
  43.         float **x;
  44.         if (x = calloc(9, sizeof(float *))) == 0)
  45.             exit(EXIT_FAILURE);
  46.     }
  47.  
  48. 4) calloc zeros out memory.  This does not mean that pointers are set to
  49.     NULL or that floating values are set to a value of floating point
  50.     zero.  It is also true that this is frequently wasted effort even
  51.     for integral values.  malloc() is usually what you want:
  52.     #include <stdlib.h>
  53.     {
  54.         float **x;
  55.         if (x = malloc(9*sizeof(float *))) == 0)
  56.             exit(EXIT_FAILURE);
  57.     }
  58.  
  59. 5) Hard coding constant values is usually a mistake:
  60.     #include <stdlib.h>
  61.     #define ARRAYSIZE   9
  62.     {
  63.         float **x;
  64.         if (x = malloc(ARRAYSIZE*sizeof(float *))) == 0)
  65.             exit(EXIT_FAILURE);
  66.     }
  67.                                                               
  68. --
  69. * Martin Ambuhl       net: mambuhl@ripco.com
  70. * Chicago, IL (USA)    
  71.